import 'dart:async';
import 'dart:io';

import 'package:starkylin_file_shared/type/type.dart';

class SocketServer {
  late HttpServer server; //服务端
  final List<WebSocket> serverSockets = []; //服务端socket
  Function(MessageInfo msg)? serverReceived;
  Completer<void> connCompleter = Completer();

  bool isBinding = false;
  bool isContinueSendSteam = true; //是否可以发送Steam
  HttpRequest? _currentRequest;
  String address = "";

  // 服务端操作
  Future<void> serverBind(int port,
      {void Function(dynamic msg)? handler,
      void Function(String ip)? onConnected}) async {
    server = await HttpServer.bind('0.0.0.0', port);
    isBinding = true;

    server.listen((HttpRequest req) async {
      _currentRequest = req; // 保存当前请求对象
      //监听"msg"数据
      address = req.connectionInfo!.remoteAddress.address;
      print("listen!!!!!!!!!! $address");
      onConnected?.call(address);

      if (WebSocketTransformer.isUpgradeRequest(req)) {
        await WebSocketTransformer.upgrade(req).then((webSocket) {
          webSocket.listen(handler, onDone: () {
            serverSockets.remove(webSocket);
            if (serverSockets.isEmpty) {
              stopServer();
            }
          });
          serverSockets.add(webSocket);
          connCompleter.complete();
        });
      }
    });
  }

  Future<void> stopServer() async {
    for (var webSocket in serverSockets) {
      await webSocket.close();
      serverSockets.remove(webSocket);
    }
    await server.close();
    isBinding = false;
    connCompleter = Completer();
  }

  String getClientIp() {
    if (_currentRequest != null) {
      return address;
    } else {
      return 'Unknown';
    }
  }

  //服务端发送消息
  void serverSendMsg(String msg, {WebSocket? socket, int? index}) {
    if (socket == null && serverSockets.contains(socket)) {
      socket!.add(msg);
    } else if (index != null && serverSockets.length > index) {
      serverSockets[index].add(msg);
    } else {
      for (var socket in serverSockets) {
        socket.add(msg);
      }
    }
  }

  //服务端发送data消息
  void serverSendDatas(List<int> datas, {WebSocket? socket, int? index}) {
    if (socket == null && serverSockets.contains(socket)) {
      socket!.add(datas);
    } else if (index != null && serverSockets.length > index) {
      serverSockets[index].add(datas);
    } else {
      for (var socket in serverSockets) {
        socket.add(datas);
      }
    }
  }
}
